#pragma once

#include <iostream>
#include <queue>
#include <pthread.h>
#include "Log.hpp"
#include "Task.hpp"

#define NUM 5

class ThreadPool
{
private:
    int _num; // 线程数量
    bool _stop; // 线程是否停止
    std::queue<Task> _task_queue; // 任务队列
    pthread_mutex_t _lock; // 锁
    pthread_cond_t _cond; // 条件变量

    ThreadPool(int num = NUM)
        : _num(num)
        , _stop(false)
    {
        pthread_mutex_init(&_lock, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    ThreadPool(const ThreadPool &)
    {}

    static ThreadPool *single_instance;

public:
    static ThreadPool *GetInstance()
    {
        static pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;
        if (single_instance == nullptr)
        {
            pthread_mutex_lock(&_mutex);
            if (single_instance == nullptr)
            {
                single_instance = new ThreadPool();
                single_instance->InitThreadPool();
            }
            pthread_mutex_unlock(&_mutex);
        }
        return single_instance;
    }

    bool IsStop()
    {
        return _stop;
    }
    bool TaskQueueIsEmpty()
    {
        return _task_queue.size() == 0 ? true : false;
    }
    void Lock()
    {
        pthread_mutex_lock(&_lock);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&_lock);
    }
    void ThreadWait()
    {
        pthread_cond_wait(&_cond, &_lock);
    }
    void ThreadWakeup()
    {
        pthread_cond_signal(&_cond);
    }
    static void *ThreadRoutine(void *args)
    {
        ThreadPool *tp = (ThreadPool *)args;

        while (true)
        {
            Task t;
            tp->Lock();
            while (tp->TaskQueueIsEmpty())
            {
                tp->ThreadWait(); // 线程唤醒时，一定占有互斥锁
            }
            tp->PopTask(t);
            tp->Unlock();
            t.ProcessOn();
        }
    }
    bool InitThreadPool()
    {
        for (int i = 0; i < _num; i++)
        {
            pthread_t tid;
            if (pthread_create(&tid, nullptr, ThreadRoutine, this) != 0)
            {
                LOG(FATAL, "create thread pool error!");
                return false;
            }
        }
        LOG(INFO, "create thread pool success!");
        return true;
    }
    void PushTask(const Task &task) // in
    {
        Lock();
        _task_queue.push(task);
        Unlock();
        ThreadWakeup();
    }
    void PopTask(Task &task) // out
    {
        task = _task_queue.front();
        _task_queue.pop();
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_cond);
    }
};

ThreadPool *ThreadPool::single_instance = nullptr;